package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.dto.order.ConsumeTradeParaDTO;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PayToolUtil;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.dto.GoodsDTO;
import com.yuanfeng.payment.entity.PayConsumeTradeEntity;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeBackMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeMapper;
import com.yuanfeng.payment.service.PayConsumeTradeService;
import com.yuanfeng.payment.vo.CallBackVO;
import com.yuanfeng.payment.vo.RecordVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName PayConsumeTradeServiceImpl
 * @Description 交易订单表-强调唯一订单-充值则先创建充值订单
 * @Author cyp
 * @Date 2023-05-31 16:13:57
 * @Version 1.0
 **/
@Service
public class PayConsumeTradeServiceImpl extends ServiceImpl<PayConsumeTradeMapper, PayConsumeTradeEntity>
        implements PayConsumeTradeService {
    @Resource
    private PayConsumeTradeBackMapper payConsumeTradeBackMapper;

    @Resource
    private PayConsumeRecordMapper payConsumeRecordMapper;

    final Logger log = LoggerFactory.getLogger(PayConsumeTradeServiceImpl.class);

    @Override
    @Transactional
    public boolean insert(ConsumeTradeParaDTO ctp) {
        String orderId = ctp.getOrderId();
        String paymentNumber = ctp.getPaymentNumber();
        // 支付单号
        String consumeTradeId = paymentNumber;
        String userId = ctp.getUserId();
        String sellerId = ctp.getSellerId();
        String payUserId = userId;
        // 订单状态
        Integer orderStateId = 1;
        // 交易类型
        Integer tradeTypeId = 1;
        // 支付渠道
        Integer paymentChannelId = 1;
        // 实付金额，在线支付金额
        BigDecimal tradePaymentAmount = ctp.getTotalPrice();
        BigDecimal orderPaymentAmount = tradePaymentAmount;
        BigDecimal tradeDiscount = ctp.getTradeDiscount();
        String tradeDate = DateUtils.getYear() + "-" + DateUtils.getMonth() + "-" + DateUtils.getDay();
        String tradeYear = DateUtils.getYear();
        String tradeMonth = DateUtils.getMonth();
        String tradeDay = DateUtils.getDay();
        String tradeTitle = "购物";
        List<String> goodsName = ctp.getGoodsName();
        //兑换积分商品所需的积分
        Integer totalIntegral = null;
        Integer integralGoods = ctp.getIntegralGoods();
        if(null != ctp.getTotalIntegral()){
            totalIntegral=ctp.getTotalIntegral();
        }
        String tradeDesc = goodsName.get(0);
        String tradeRemark = "";
        String tradeCreateTime = DateUtils.getNowDateToString();
        boolean isInsertSuccess = this.baseMapper.insertConsumeTrade(consumeTradeId, orderId, userId, sellerId, payUserId,
                orderStateId, tradeTypeId, paymentChannelId, orderPaymentAmount, tradePaymentAmount, tradeDiscount,
                tradeDate, tradeYear, tradeMonth, tradeDay, tradeTitle, tradeDesc, tradeRemark, tradeCreateTime,totalIntegral,integralGoods);
        return isInsertSuccess;
    }

    @Override
    public List<CallBackVO> treasureOrder(String token, String orderId) {
        List<CallBackVO> callBackParaList = null;
        try {
            // 获取user信息
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(token);
            String userId = ui.getUserId();
            String userName = ui.getUserName();

            callBackParaList = new ArrayList<CallBackVO>();
            CallBackVO callBackPara = new CallBackVO();
            callBackPara.setUserId(userId.toString());
            callBackPara.setUserName(userName);
            String treasureShopId = null;

            if (PayToolUtil.isInteger(orderId)) {
                GoodsDTO queryGoodsPara = payConsumeTradeBackMapper.queryGoodsPriceAndName(orderId, userId);
                BigDecimal paymentAmount = queryGoodsPara.getTradePaymentAmount();
                treasureShopId = this.baseMapper.queryTreasureShopIdByInt(orderId);
                callBackPara.setOrderFullAmount(paymentAmount.toString());
                callBackPara.setShopId(treasureShopId);
                callBackParaList.add(callBackPara);
            } else {

                List<RecordVO> rp = payConsumeRecordMapper.queryRecordParaList(orderId);
                log.info("rp============", rp);
                for (int i = 0; i < rp.size(); i++) {
                    log.info("rp.size()============", rp.size());
                    callBackPara = new CallBackVO();
                    callBackPara.setUserName(userName);
                    callBackPara.setUserId(userId.toString());
                    log.info("=========callBackPara====" + JSON.toJSONString(rp) + "===============");
                    String str[] = rp.get(i).getRecordPayorder().split(",");

                    List<String> shopIdList = Arrays.asList(str);

                    log.info("=======shopIdList======" + JSON.toJSONString(shopIdList) + "===============");
                    for (int j = 0; j < shopIdList.size(); j++) {
                        treasureShopId = this.baseMapper.queryTreasureShopIdByInt(shopIdList.get(j));
                        callBackPara.setShopId(treasureShopId);
                    }
                    callBackPara.setOrderFullAmount(rp.get(i).getRecordMoney().toString());
                    callBackParaList.add(callBackPara);
                }
            }

            log.info("-----treasure======Order-----");
        } catch (Exception e) {
            log.info("-----treasureOrder-----" + e.getMessage());
        }
        return callBackParaList;
    }

    @Override
    public String queryOrderId(String orderId) {
        return this.baseMapper.queryOrderId(orderId);
    }
}
